package com.lcz.audioplayer;

import android.media.MediaPlayer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * 作者:     刘传政
 * 创建时间:  14:16 2024/4/1 0001
 * QQ:      1052374416
 * 电话:     18501231486
 * 描述:     对mediaplayer的简单封装
 */
public class PlayerManager implements IManager {
    public static final int STATE_NO = -1;
    public static final int STATE_PREPARING = 2;
    public static final int STATE_PREPARED = 3;

    public static final int STATE_PLAYING = 3;

    public static final int STATE_PAUSE = 4;

    public static final int STATE_STOP = 5;
    private int mState = STATE_NO;
    String TAG = PlayerManager.class.getSimpleName();
    private SimpleDateFormat mMinFormat = new SimpleDateFormat("mm:ss");
    private SimpleDateFormat mHourFormat = new SimpleDateFormat("hh:mm:ss");
    private MediaPlayer mMediaPlayer;
    String url = "";
    private final Handler mHandler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            updateProgress();
        }
    };
    private PlayerManagerCallback callback;
    public String getPlayUrl(){
        return url;
    }
    @Override
    public int getState(){
        return mState;
    }
    public PlayerManager() {
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
        }
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mState = STATE_PREPARED;
                mMediaPlayer.start();
                mState = STATE_PLAYING;
                updateProgress();
                if (callback != null) {
                    callback.onPlayStart();
                }
            }
        });
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                if (callback != null) {
                    callback.onPlayError(mp,what,extra);
                }
                return false;
            }
        });
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (callback != null) {
                    callback.onCompletion();
                }
            }
        });

    }
    public void setCallBack(PlayerManagerCallback callback){

        this.callback = callback;
    }
    private void log(String msg){
        Log.i(TAG, msg);
    }
    /**
     * 更新进度
     */
    private void updateProgress() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {

            if (callback != null) {
                int currentPosition = mMediaPlayer.getCurrentPosition();
                int total = mMediaPlayer.getDuration();
                String totalDurationStr;
                String currentPositionStr;
                if (total > 1000 * 60 * 60) {
                    totalDurationStr = mHourFormat.format(total);
                    currentPositionStr = mHourFormat.format(currentPosition);
                } else {
                    totalDurationStr = mMinFormat.format(total);
                    currentPositionStr = mMinFormat.format(currentPosition);
                }
                log("[currentPosition-"+currentPosition+"]"+"[currentPositionStr-"+currentPositionStr+"]"+"[total-"+total+"]"+"[totalDurationStr-"+totalDurationStr+"]");
                callback.onProgressChange(currentPosition,total,currentPositionStr,totalDurationStr);
            }
            mHandler.postDelayed(runnable, 1000);
        }
    }
    @Override
    public void start(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        if (this.url.equals(url) && (mState == STATE_PLAYING || mState == STATE_PAUSE || mState == STATE_PREPARED)) {
            mMediaPlayer.start();
            mState = STATE_PLAYING;
            updateProgress();
            if (callback != null) {
                callback.onPlayStart();
            }
        }else {
            mMediaPlayer.reset();
            mHandler.removeCallbacks(runnable);
            try {
                mMediaPlayer.setDataSource(url);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            mMediaPlayer.prepareAsync();
            mState = STATE_PREPARING;
        }
        this.url = url;

    }
    public void pause() {
        try {
            if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                mMediaPlayer.pause();
                if (callback != null) {
                    mState = STATE_PAUSE;
                    callback.onPlayPause();
                }
                mHandler.removeCallbacks(runnable);
            }
        } catch (Exception e) {

        }

    }
    public void seekTo(int position) {
        if (mMediaPlayer != null) {
            mMediaPlayer.seekTo(position);
        }
    }
    public void stop() {
        if (mMediaPlayer != null && (mMediaPlayer.isPlaying())) {
            mMediaPlayer.stop();
            mState = STATE_STOP;
            if (callback != null) {
                callback.onPlayStop();
            }
            mHandler.removeCallbacks(runnable);
        }
    }

    @Override
    public int getDuration() {
        return mMediaPlayer == null ? -1 : mMediaPlayer.getDuration();
    }

    @Override
    public boolean isPlaying() {
        return mMediaPlayer.isPlaying();
    }


}
